import { NextRequest, NextResponse } from 'next/server'
import { getToolReviews, addReview, type StoredReview } from '@/lib/database'
import { requireAuth, withErrorHandling } from '@/lib/auth-middleware'
import { reviewValidation, validateInput } from '@/lib/validation'
import { randomUUID } from 'crypto'

// 获取工具的评价（无需认证）
export const GET = withErrorHandling(async (request: NextRequest, context?: { params: Promise<{ id: string }> }) => {
  if (!context?.params) {
    return NextResponse.json(
      { error: '缺少工具ID参数' },
      { status: 400 }
    )
  }

  const { id } = await context.params
  const reviews = await getToolReviews(id)

  return NextResponse.json({
    success: true,
    data: reviews
  })
})

// 添加评价（需要认证）
export const POST = withErrorHandling(async (request: NextRequest, context?: { params: Promise<{ id: string }> }) => {
  return requireAuth(request, async (req) => {
    if (!context?.params) {
      return NextResponse.json(
        { error: '缺少工具ID参数' },
        { status: 400 }
      )
    }

    const { id } = await context.params
    const body = await request.json()

    // 验证输入数据
    const validation = validateInput(reviewValidation.create, body)
    if (!validation.success) {
      return NextResponse.json(
        { error: '输入数据无效', details: validation.errors },
        { status: 400 }
      )
    }

    const { rating, comment } = validation.data

    // 获取当前用户信息
    const user = req.user!

    // 创建评价
    const review: StoredReview = {
      id: randomUUID(),
      toolId: id,
      userId: user.id,
      rating: rating,
      comment: comment,
      createdAt: new Date().toISOString(),
      updatedAt: new Date().toISOString(),
      user: {
        name: user.name,
        avatar: undefined // 暂时不支持头像
      }
    }

    await addReview(review)

    return NextResponse.json({
      success: true,
      data: review,
      message: '评价添加成功'
    })
  })
})
